package com.dc.datacollect.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.datacollect.constant.InviteCodeConstant;
import com.dc.datacollect.constant.type.UserType;
import com.dc.datacollect.dto.SysUserDTO;
import com.dc.datacollect.dto.input.CreateGroupItemInput;
import com.dc.datacollect.dto.input.RenameGroupInput;
import com.dc.datacollect.dto.output.FindGroupItemOutput;
import com.dc.datacollect.entity.GroupItem;
import com.dc.datacollect.entity.Part;
import com.dc.datacollect.service.GroupItemService;
import com.dc.datacollect.mapper.GroupItemMapper;
import com.dc.datacollect.service.PartService;
import com.dc.datacollect.helpers.SessionProvide;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author zhuangjie
* @description 针对表【group_item(收集组)】的数据库操作Service实现
* @createDate 2023-06-20 20:32:16
*/
@Service
public class GroupItemServiceImpl extends ServiceImpl<GroupItemMapper, GroupItem>
    implements GroupItemService{

    @Autowired
    private PartService partService;



    @Override
    public String createGroupItem(CreateGroupItemInput groupItemInput) throws Exception {
        LambdaQueryWrapper<GroupItem> groupItemQueryWrapper = new LambdaQueryWrapper<>();
        groupItemQueryWrapper.eq(GroupItem::getName,groupItemInput.getGroupItemName());
        groupItemQueryWrapper.eq(GroupItem::getGroupsId,groupItemInput.getGroupsId());
        GroupItem groupItem = this.getOne(groupItemQueryWrapper);
        if (groupItem != null ) {
            throw new Exception("当前集合下已经有同名收集组");
        }

        GroupItem newGroupItem = new GroupItem();
        newGroupItem.setName(groupItemInput.getGroupItemName());
        newGroupItem.setGroupsId(groupItemInput.getGroupsId());
        this.save(newGroupItem);
        // 查出刚才插入的收集组完整信息
        groupItem  = this.getOne(groupItemQueryWrapper);
        if (groupItem == null) {
            throw new Exception("创建组失败");
        }
        return genInviteCode(groupItem.getId());
    }

    @Override
    public boolean removeGroupsById(Long groupItemId) {
        return this.removeById(groupItemId);
    }


    public String genInviteCode(Long groupItemId) {
        String source = String.valueOf(groupItemId);
        if (source.length() < InviteCodeConstant.MIN_LENGTH) {
            String FULL = new String(new char[4]).replace("\0", String.valueOf(InviteCodeConstant.NULL_UNIT));
            String rawCode = FULL + source;
            return rawCode.substring(rawCode.length() - 4);
        }

        return source;
    }
     public String parentInviteCode(String code) {
        // code就是由groupItemId生成的，现在反转
        int index = 0;
        for (; index < code.length(); index++) {
            // 找到第一个不为指定字符的位置
            if (code.charAt(index) != InviteCodeConstant.NULL_UNIT) {
                break;
            }
        }
        // 返回该位置之后的子串
        return code.substring(index);
    }

    @Override
    public FindGroupItemOutput find(String code) {
        String groupItemId = this.parentInviteCode(code);
        GroupItem groupItem = this.getById(groupItemId);
        // 查出这个收集组中的加入的人数
        LambdaQueryWrapper<Part> partQueryWrapper = new LambdaQueryWrapper<>();
        partQueryWrapper.eq(Part::getGroupId,groupItemId);
        long count = partService.count(partQueryWrapper);
        // 查看用户是否已经加入
        LambdaQueryWrapper<Part> finUserJoinGroupQueryWrapper = new LambdaQueryWrapper<>();
        finUserJoinGroupQueryWrapper.eq(Part::getUserId,SessionProvide.getLoginObject().getId())
                .eq(Part::getGroupId,groupItemId);
        Part finUserJoinGroupPart = partService.getOne(finUserJoinGroupQueryWrapper);

        FindGroupItemOutput findGroupItemOutput = new FindGroupItemOutput();
        findGroupItemOutput.setGroupItem(groupItem);
        findGroupItemOutput.setCount(count);
        findGroupItemOutput.setIsJoined(finUserJoinGroupPart != null);
        return findGroupItemOutput;
    }

    @Override
    public Boolean joinGroup(Long groupItemId) throws Exception {
        SysUserDTO loginObject = SessionProvide.getLoginObject();
        // 判断用户类型，只能是普通用户（被收集者）才能加入
        if (loginObject.getType().equals(UserType.COLLECTOR)) {
            throw new Exception("你是收集者账号，不能加入");
        }
        // 查出这个组，如果不存在，就无法加入
        GroupItem groupItem = this.getById(groupItemId);
        if ( groupItem == null ) {
            throw new Exception("组不存在");
        }
        // 组存在，判断是否已经加入
        LambdaQueryWrapper<Part> partQueryWrapper = new LambdaQueryWrapper<>();
        partQueryWrapper.eq(Part::getGroupId,groupItemId)
                .eq(Part::getUserId,loginObject.getId());
        Part part = partService.getOne(partQueryWrapper);
        if (part != null) {
            throw new Exception("你已经加入！");
        }
        Part newPart = new Part();
        newPart.setGroupId(groupItemId);
        newPart.setUserId(loginObject.getId());
        return partService.save(newPart);
    }

    @Override
    public Boolean rename(RenameGroupInput renameGroupInput) throws Exception {
        GroupItem groupItem = this.getById(renameGroupInput.getGroupId());
        if (groupItem == null ) {
            throw new Exception("重命名的组不存在！");
        }
        groupItem.setName(renameGroupInput.getNewName());
        return this.updateById(groupItem);
    }

}




